
package com.boot.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.boot.controller.PushController;
import com.boot.entity.*;
import com.boot.mapper.AdDao;
import com.boot.mapper.PushDao;
import com.boot.mapper.UserDao;
import com.boot.service.CodeService;
import com.boot.service.StoreService;
import com.boot.service.UserService;
import com.boot.util.*;
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

@Service("userService")
@Transactional
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
	private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
	@Resource
	private UserDao userDao;
	@Resource
	private CodeService codeService;
	@Resource
	private StoreService sotreService;
	@Resource
	private AdDao addao;
	@Resource
	private PushDao pushDao;

	@Override
	public User login(HashMap<String, Object> params) {
		User user = userDao.login(params);
		return user;
	}

	@Override
	@Transactional
	public AdResult register(String username,String phone, String login_password, Integer code) throws Exception {
		System.out.println(username+":"+phone+":"+login_password);
		AdResult result = new AdResult();
		// 当用户输入的电话号码不为空时再判断是否已经注册过
		if (!phone.equals("")) {
			User user = userDao.findByPhone(phone);
			if (user != null) {
				result.setStatus(0);
				result.setMsg("您已注册过,请直接登录!");
				return result;
			}
		}
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("phone", phone);
		params.put("code", code);
		// 如果还没进行长连接注册，并且未注册过
		if (username==null) {//123456时临测试设置的验证码
			// 直接进行注册
			params.put("password", login_password);
			User addUser = new User();
			addUser.setLogin_password(EncodeUtil.md5(login_password+"xggdxc"));
			addUser.setPhone(phone);
			Date created_time = new Date();
			addUser.setCreated_date(created_time);
			userDao.save(addUser);
			result.setStatus(1);
			result.setMsg("注册成功!");
			return result;
		} else {// add by yedong
			Code getCode = codeService.findByPhone(params);
			if (getCode == null) {
				result.setStatus(0);
				result.setMsg("验证码错误,请重试!");
				return result;
			} else {
				int now = (int) (System.currentTimeMillis() / 1000);
				int a = getCode.getEndtime() - now;
				Integer code2 = getCode.getCode();
				if (code2.equals(code) && (a > 0)) {
					User addUser = new User();
					addUser.setLogin_password(EncodeUtil.md5(login_password+"xggdxc"));
					addUser.setPhone(phone);
					int resultcode =0;
					if (resultcode > 0) {
						result.setStatus(1);
						result.setMsg("注册成功!");
						return result;
					} else {
						result.setStatus(0);
						result.setMsg("注册失败!");
						return result;
					}
					// 同时初始化我的店铺
					// Store store = new Store();
					// store.setId(addUser.getId());
					// store.setTel(phone);
					// store.setName(phone);
					// sotreService.createStore(store);
				} else if (a < 0) {
					result.setStatus(0);
					result.setMsg("验证码超时,请重新发送!");
					return result;
				} else {
					result.setStatus(0);
					result.setMsg("验证码错误,请重试!");
					return result;
				}
			}
		}

	}

	@Override
	public AdResult getCode(String phone) {
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(Url);
		AdResult result = new AdResult();
		User user = userDao.findByPhone(phone);
//		if (user != null) {
//			result.setStatus(0);
//			result.setMsg("您已注册过,请直接登录!");
//			return result;
//		}
		client.getParams().setContentCharset("GBK");
		method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");

		int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);

		String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");

		NameValuePair[] data = { // 提交短信
				new NameValuePair("account", "cf_18753916953"), // 查看用户名是登录用户中心->验证码短信->产品总览->APIID
				new NameValuePair("password", "db68a0043ba3d796d2ad17d63acd832b"), // 查看密码请登录用户中心->验证码短信->产品总览->APIKEY
				// new NameValuePair("password",
				// util.StringUtil.MD5Encode("密码")),
				new NameValuePair("mobile", phone), new NameValuePair("content", content), };
		method.setRequestBody(data);

		try {
			client.executeMethod(method);

			String SubmitResult = method.getResponseBodyAsString();

			Document doc = DocumentHelper.parseText(SubmitResult);
			Element root = doc.getRootElement();

			String code = root.elementText("code");
			String msg = root.elementText("msg");
			String smsid = root.elementText("smsid");

			System.out.println(code);
			System.out.println(msg);
			System.out.println(smsid);

			if ("2".equals(code)) {
				Code yzcode = new Code();
				yzcode.setCode(mobile_code);
				yzcode.setPhone(phone);
				yzcode.setEndtime((int) (System.currentTimeMillis() / 1000 + 300));
				codeService.save(yzcode);
				System.out.println("短信提交成功");
				result.setStatus(1);
				result.setMsg("发送成功!");

			} else {
				result.setStatus(0);
				result.setMsg("发送失败,请重试!");
			}

		} catch (HttpException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		} catch (DocumentException e) {

			e.printStackTrace();
		}
		return result;
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)//开启事务
	public AdResult login(String phone, String login_password) {
		System.out.println("login_pwd:"+EncodeUtil.md5(login_password));
		AdResult result = new AdResult();
		User findUser = userDao.findByPhone(phone);
		System.out.println("findUser:"+findUser);
		if (findUser == null) {
			result.setStatus(0);
			result.setMsg("用户不存在!");
			return result;
		} else {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("phone", phone);
			try {
				params.put("login_password", EncodeUtil.md5(login_password));
			} catch (Exception e) {
				e.printStackTrace();
			}
			User user = this.login(params);
			if (user != null) {
				result.setData(user);
				result.setStatus(1);
				result.setMsg("登陆成功!");
				return result;
			} else {
				result.setStatus(0);
				result.setMsg("用户名或密码错误!");
			}
			return result;
		}

	}

	@Override
	public AdResult getMyAds(String user_id, int pageIndex, int pageSize) {
		AdResult result = new AdResult();
		// 定义一个map用于存放请求参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("pageIndex", (pageIndex - 1) * pageSize);
		params.put("pageSize", pageSize);
		// 调用dao接口获取广告
		List<Ad> myads = userDao.getMyAds(params);
		// 如果获取的数据不为空
		if (myads != null) {
			result.setStatus(1);
			result.setData(myads);
			result.setMsg("获取成功");
		} else {
			result.setMsg("没有数据");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult deleteAd(String ad_id) {
		// String path=this.getClass().getResource(File.separator).toString();
		// String projectPath=path.split("WEB-INF")[0];
		// System.out.println(projectPath);
		AdResult result = new AdResult();
		/*
		 * 删除数据库中的记录时同事删除其对应的图片,利用file类操作文件删除
		 * 思路：删除之前先拿到广告对象本身，获取广告的图片地址信息，再拿到项目所在的根目录就可以锁定文件所在位置 进而将其删除 步骤
		 * 1、先获取到某条广告 2、将数据库中存的广告对象删除 3、将该条广告的所有图片的数据库地址信息保存至一个数组中存储 4、拿到项目根目录
		 * 5、逐个删除图片
		 */
		// 1获取广告本身
		Ad ad = addao.getAdById(ad_id);
		// 2、删除数据库中的广告对象
		int resultcode = userDao.deleteAd(ad_id);
		// 3、删除推送表中的数据
		if(ad.getIspush()==1){
			int deletePushResult=pushDao.deletePush(ad_id);
		}
		if (resultcode > 0) {
			String filePaths = null;
			String[] thrumFilePaths = null;
			// 3、创建保存图片地数组并初始化
			if (ad.getPhotos() != null) {
				filePaths = ad.getPhotos();//将其转成集合
	
				// 4、项目根目录D:\Users\Administrator\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\adlet\
				// String
				// projectPath="D:"+File.separator+"Users"+File.separator+"Administrator"+File.separator+"workspace"+File.separator+
				// ".metadata"+File.separator+".plugins"+File.separator+"org.eclipse.wst.server.core"+File.separator+
				// "tmp1"+File.separator+"wtpwebapps"+File.separator+"adlet"+File.separator+"";
				String path = this.getClass().getResource(File.separator).getPath().toString();
				String projectPath = path.split("WEB-INF")[0];
				// System.out.println(projectPath);
				// 5、循环删除图片
				//TODO
//				for (int i = 0; i < filePaths.size(); i++) {
//					// 创建文件
//					File file = new File(projectPath + filePaths.get(i));
//					if (file.exists()) {
//						file.delete();
//					}
//				}
			}
			result.setMsg("删除成功");
			result.setStatus(1);
		} else {
			result.setMsg("删除失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult saveUserLocation(UserLocation userLocation) {
		AdResult result = new AdResult();
		// 获取当前系统时间
		userLocation.setTime(new Date());
		int resultcode = userDao.saveUserLocation(userLocation);
		if (resultcode > 0) {
			result.setStatus(1);
			result.setMsg("保存成功");
		} else {
			result.setStatus(0);
			result.setMsg("保存失败");
		}
		return result;
	}

	@Override
	public AdResult getUserInfo(String user_id,String token) {
		AdResult result = new AdResult();
		HashMap<String, String> map=new HashMap<>();
		map.put("user_id",user_id);
		map.put("token",token);
		User userInfo = userDao.getUserInfo(map);
		if (userInfo != null) {
			String job_id=userInfo.getJob_id();
			String job_id_second=userInfo.getJob_id_second();
			String job_id_third=userInfo.getJob_id_third();
			if(job_id!=null && job_id_second!=null && job_id_third!=null){
				String job_id_f=job_id+","+job_id_second+","+job_id_third;
				userInfo.setJob_id(job_id_f);
			}else if(job_id!=null && job_id_second!=null){
				String job_id_f=job_id+","+job_id_second;
				userInfo.setJob_id(job_id_f);
			}
			result.setData(userInfo);
			result.setMsg("获取用户详细信息成功");
			result.setStatus(1);
		} else {
			result.setMsg("获取失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult getBalance(String id) {
		AdResult result = new AdResult();
		User user = userDao.getBalance(id);
		if (user != null) {
			result.setData(user);
			result.setMsg("获取用户余额成功");
			result.setStatus(1);
		} else {
			result.setMsg("获取失败");
			result.setStatus(0);
		}
		return result;
	}
		
	@Override
	public AdResult update(User user) {
		AdResult result = new AdResult();
		String job_id=user.getJob_id();
		if(job_id!=null){
			String[] job_ids=job_id.split(",");
			for(int i=0;i<job_ids.length;i++){
				if(i==0){
					user.setJob_id(job_ids[0]);
				}
				if(i==1){
					user.setJob_id_second(job_ids[1]);
				}
				if(i==2){
					user.setJob_id_third(job_ids[2]);
				}
			}
		}
		int resultn = userDao.updatenoicon(user);
		if (resultn > 0) {
			result.setMsg("修改成功!");
			result.setStatus(1);
		} else {
			result.setMsg("修改成失败!");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult update(User user, HttpServletRequest request,@RequestParam(value = "file", required = false) CommonsMultipartFile file) {
		String job_id=user.getJob_id();
		if(job_id!=null){
			String[] job_ids=job_id.split(",");
			for(int i=0;i<job_ids.length;i++){
				if(i==0){
					user.setJob_id(job_ids[0]);
				}
				if(i==1){
					user.setJob_id_second(job_ids[1]);
				}
				if(i==2){
					user.setJob_id_third(job_ids[2]);
				}
			}
		}
		// 头像的压缩后的在当前项目的存储地址
		String iconPath = "";
		// 获取项目的根目录
		String basePath = request.getSession().getServletContext().getRealPath(File.separator);
		// 如果文件不为空
		if (!file.isEmpty()) {
			// 定义头像图片相对项目根目录的存放的地址
			iconPath = "upload" + File.separator + "icon" + File.separator + user.getUser_id() + ".png";
			// 压缩并上传
			CompressImageUtil.compressByWH(file, basePath + iconPath);
			
		}
		// 将压缩后的地址字符串存入到user对象中
		user.setIcon(iconPath);
		// 创建结果对象
		AdResult result = new AdResult();
		// 调用dao接口写入到数据库
		int i = userDao.update(user);
		if (i > 0) {
			result.setMsg("修改成功");
			result.setStatus(1);
		} else {
			result.setMsg("修改失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult getJobCode() {
		AdResult result=new AdResult();
		List<JobCode> jobCodes=new ArrayList<>();//最终获取到的结果
		List<Job> firstJobs=new ArrayList<>();
		List<Job> secondJobs=new ArrayList<>();
		List<Job> thirdJobs=new ArrayList<>();
		List<Job> jobs=userDao.getJobCode();
		System.out.println(jobs);
		if(jobs!=null){
			//把每个对象分门别类，并筛选出第一类来
			JobCode jobCode;
			for(int i=0;i<jobs.size();i++){
				if((Integer.parseInt(jobs.get(i).getJobcode())%10000) == 0){
					jobCode=new JobCode();
					firstJobs.add(jobs.get(i));
					jobCode.setId(jobs.get(i).getId());
					jobCode.setJobcode(jobs.get(i).getJobcode());
					jobCode.setJobname(jobs.get(i).getJobname());
					jobCodes.add(jobCode);
				}else if((Integer.parseInt(jobs.get(i).getJobcode())%100) == 0){
					secondJobs.add(jobs.get(i));
				}else{
					thirdJobs.add(jobs.get(i));
				}
			}
			//筛选第二种行业
			List<JobCodeSecond> jobCodeSeconds;
			JobCodeSecond jobCodeSecond;
			for(int i=0;i<jobCodes.size();i++){
				jobCodeSeconds=new ArrayList<>();
				for(int j=0;j<secondJobs.size();j++){
					if(Integer.parseInt(secondJobs.get(j).getJobcode())/10000 == Integer.parseInt(jobCodes.get(i).getJobcode())/10000){
						jobCodeSecond=new JobCodeSecond();
						jobCodeSecond.setId(secondJobs.get(j).getId());
						jobCodeSecond.setJobcode(secondJobs.get(j).getJobcode());
						jobCodeSecond.setJobname(secondJobs.get(j).getJobname());
						jobCodeSeconds.add(jobCodeSecond);
					}
				}
				if(jobCodeSeconds.size()>0){
					jobCodes.get(i).setSecondJob(jobCodeSeconds);
				}
			}
			//筛选第三种行业
			List<JobCodeThird> jobCodeThirds;
			JobCodeThird jobCodeThird;
			for(int i=0;i<jobCodes.size();i++){
				for(int j=0;j<jobCodes.get(i).getSecondJob().size();j++){
					jobCodeThirds=new ArrayList<>();
					for(int k=0;k<thirdJobs.size();k++){
						if(Integer.parseInt(jobCodes.get(i).getSecondJob().get(j).getJobcode())/100 == Integer.parseInt(thirdJobs.get(k).getJobcode())/100 ){
							jobCodeThird=new JobCodeThird();
							jobCodeThird.setId(thirdJobs.get(k).getId());
							jobCodeThird.setJobcode(thirdJobs.get(k).getJobcode());
							jobCodeThird.setJobname(thirdJobs.get(k).getJobname());
							jobCodeThirds.add(jobCodeThird);
						}
					}
					if(jobCodeThirds.size()>0){
						System.out.println(jobCodeThirds);
						jobCodes.get(i).getSecondJob().get(j).setJobCodeThirds(jobCodeThirds);
					}
				}
			}
		}
		//System.out.println("jobCodes:"+jobCodes);
		if(jobCodes.size()>0){
			result.setData(jobCodes);
			result.setMsg("获取行业职业");
			result.setStatus(1);
		}else{
			result.setMsg("获取行业职业失败");
			result.setStatus(0);
		}
		return result;
	}

	@Override
	public AdResult updateMyType(User user) {
		AdResult adResult=new AdResult();
		int resultCode=userDao.updateMyType(user);
		if(resultCode>0){
			adResult.setMsg("修改成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("修改失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public String getMyType(String id) {
		List<User> users=userDao.getMyType(id);
		String myType="";
		if(users.size()>0){
			myType=users.get(0).getMyType();
		}
		return myType;
	}

	/**
	 * 根据圈点获取在圈内的用户集合
	 * @param lon
	 * @param lat
	 * @param radius
	 * @return
	 */
	public AdResult findAll(double lon,double lat,int radius){
		AdResult adResult=new AdResult();
		List<User> users=userDao.findAllLocations();
		Iterator<User> iterator = users.iterator();
		while (iterator.hasNext()){
			User user = iterator.next();
			Double lng = user.getLon();
			Double lat1 = user.getLat();
			double getDistance = MapUtils.GetDistance(lon,lat,lng,lat1);

			if(getDistance>radius){
				iterator.remove();
			}
		}
		adResult.setData(users);
		return adResult;
	}

	@Override
	public AdResult findAllAround(double lon, double lat, Double radius) {
		AdResult adResult=new AdResult();
		List<User> Users=userDao.findAllArountLocations();
		Iterator<User> iterator = Users.iterator();
		while (iterator.hasNext()){
			User userLocation = iterator.next();
			Double lng1 = userLocation.getLon();
			Double lat1 = userLocation.getLat();
			if(lng1==null || lat1==null){
				iterator.remove();
				continue;
			}
			double getDistance = MapUtils.GetDistance(lon,lat,lng1,lat1);
			if(getDistance>radius){
				iterator.remove();
			}
		}
		if(Users.size()>0){
			adResult.setMsg("获取成功");
			adResult.setStatus(1);
			adResult.setData(Users);
		}else{
			adResult.setMsg("未获取到数据");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult pushAdTop(String id) {
		AdResult adResult=new AdResult();
		int resultcode = userDao.pushAdTop(id);
		if(resultcode>0){
			adResult.setMsg("置顶成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("置顶失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult getUserInfoByPhone(String phone) {
		AdResult adResult=new AdResult();
		User user=userDao.getUserInfoByPhone(phone);
		if(user!=null){
			adResult.setData(user);
			adResult.setMsg("获取成功");
			adResult.setStatus(1);
		}else {
			adResult.setMsg("获取失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	@Transactional
	public AdResult saveAndBundleUserName(String username,String phone, String user_id,String devicetype) {
		System.out.println("username:"+username+",phone:"+phone+",user_id:"+user_id);
		AdResult adResult=new AdResult();
		//获取长连接创建的用户
		User user=userDao.getUserByUsername(username);
		if(user==null){
			//要么保存要么绑定此长连接账号
			if(!phone.equals("")){
				//已经注册、登录，进行绑定
				User userphone=userDao.findByPhone(phone);
				if(userphone!=null){
					userphone.setUsername(username);
					userphone.setDevicetype(devicetype);
					userDao.bundleUsername(userphone);
					adResult.setMsg("绑定成功");
					adResult.setStatus(1);
				}else{
					//未注册或者未登录进行保存
					user=new User();
					user.setUsername(username);
					user.setDevicetype(devicetype);
					user.setUser_id(GenerateUniqueId.generateUniqueId());
					userDao.saveUsername(user);
					adResult.setMsg("保存成功");
					adResult.setStatus(2);
				}
			}else{
				//未注册或者未登录进行保存
				user=new User();
				user.setUsername(username);
				user.setDevicetype(devicetype);
				user.setUser_id(GenerateUniqueId.generateUniqueId());
				userDao.saveUsername(user);
				adResult.setMsg("保存成功");
				adResult.setStatus(2);
			}
		}else{
			if(!phone.equals("")){
				//已经注册并登录与刚刚创建的长连接比对username
				User userphone=userDao.findByPhone(phone);
				//临时保存先前的长连接账号
				String usernameold=userphone.getUsername();
				String deviceType=userphone.getDevicetype();
				if(userphone.getUsername()==null || !userphone.getUsername().equals(username)){
					//不一致将新建的username绑定到先前创建的账号上
					userphone.setUsername(username);
					userphone.setDevicetype(devicetype);
					int result1=userDao.bundleUsername(userphone);
					//同事删掉临时创建的账号但不删除在此设备上的登录的其他账号
					if(!user.getUser_id().equals(userphone.getUser_id()) && user.getPhone()==null){
						userDao.deleteUser(user.getUser_id());
					}
					if(result1>0){
						if(usernameold!=null && !usernameold.equals("")){
							//发送下线通知
							if(deviceType.equals("a")){
								sendOffLine(usernameold);
							}else if(deviceType.equals("i")){
								sendOffLineToIos(usernameold);
							}
						}
						adResult.setMsg("重新绑定成功");
						adResult.setStatus(3);
					}
				}
			}
		}
		return adResult;
	}
	
	

	/**
	 * 发送下线通知
	 * @param username
	 */
	public void sendOffLine(String username){
		//给被迫下线的用户一个推送通知
		HashMap<String, String> map=new HashMap<String, String>();
		map.put("username", username);
		Map<String, String> urlmap = new HashMap<String, String>();
    	urlmap.put("action", "sendOffLineMessage");
		System.out.println(PushServerConfig.pushServerInterFace);
		//PushController.sendPost(PushServerConfig.pushServerIp+"notification.do?", urlmap, map);
		//本机向安卓用户发下线通知
    	PushController.sendPost(PushServerConfig.pushServerInterFace, urlmap, map);
	}
	
	/**
	 * 向ios用户发送下线通知
	 * @param usernameold
	 */
	private void sendOffLineToIos(String usernameold) {
		System.out.println("zsl==========开始推送消息");
        int badge = 1; // 图标小红圈的数值
        String sound = "default"; // 铃音
        String msgCertificatePassword = "xgg+20180524";//导出证书时设置的密码
        String deviceToken = usernameold; //手机设备token号
        String message="账号在别处登录";
        List<String> tokens = new ArrayList<String>();
        //java必须要用导出p12文件  php的话是pem文件
        //本地p12文件的路径
        //String certificatePath = "E:"+File.separator+"xggsource"+File.separator+"zhengshu"+File.separator+"aps.p12";
        //linux服务器文件路径
        //String certificatePath="/root/anps/aps.p12";
        String certificatePath=PushServerConfig.certificatePath;
        boolean sendCount = true;
        PushNotificationPayload payload = new PushNotificationPayload();
        try {
			payload.addAlert(message);
			payload.addSound(sound);
			payload.addCustomDictionary("warning", "sendoffline");
	          PushNotificationManager pushManager = new PushNotificationManager();
	          // true：表示的是产品测试推送服务 false：表示的是产品发布推送服务
	          pushManager.initializeConnection(new AppleNotificationServerBasicImpl(
	                  certificatePath, msgCertificatePassword, false));
	          List<PushedNotification> notifications = new ArrayList<PushedNotification>();
	          // 开始推送消息
	          if (sendCount) {
	        	  PushedNotification notification=null;
	        		  Device device = new BasicDevice();
	      			  payload.addBadge(1);  
		              device.setToken(deviceToken);
		              notification = pushManager.sendNotification(device, payload, true);
	              notifications.add(notification);
	          } else {
	              List<Device> devices = new ArrayList<Device>();
	              //System.out.println(tokens);
	              BasicDevice basicDevice=null;
	              for (String token : tokens) {
	            	  basicDevice=new BasicDevice(token);
	                  devices.add(basicDevice);
	              }
	              notifications = pushManager.sendNotifications(payload, devices);
	          }
	          List<PushedNotification> failedNotification = PushedNotification
	                  .findFailedNotifications(notifications);
	          List<PushedNotification> successfulNotification = PushedNotification
	                  .findSuccessfulNotifications(notifications);
	          int failed = failedNotification.size();
	          int successful = successfulNotification.size();
	          System.out.println("zsl==========成功数：" + successful);
	          System.out.println("zsl==========失败数：" + failed);
	          pushManager.stopConnection();
	          System.out.println("zsl==========消息推送完毕");
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (CommunicationException e) {
			e.printStackTrace();
		} catch (KeystoreException e) {
			e.printStackTrace();
		} catch (InvalidDeviceTokenFormatException e) {
			e.printStackTrace();
		}
	}

	@Override
	public AdResult loginWithoutPwd(String phone, Integer code,String devicetype) {
		AdResult result=new AdResult();
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("phone", phone);
		params.put("code", code);
			Code getCode = codeService.findByPhone(params);
			if (getCode == null) {
				result.setStatus(0);
				result.setMsg("验证码错误,请重试!");
				return result;
			} else {
				int now = (int) (System.currentTimeMillis() / 1000);
				int a = getCode.getEndtime() - now;
				Integer code2 = getCode.getCode();
				if (code2.equals(code) && (a > 0)) {
					//判断之前有没有注册过
					User user=userDao.findByPhone(phone);
					if(user!=null){
						user.setToken(CommonUtils.makeToken(phone));
						int resultCode=userDao.updateToken(user);
						if(resultCode>0){
							result.setStatus(1);
							result.setMsg("登录成功");
							result.setData(user);
						}else{
							result.setStatus(0);
							result.setMsg("登录失败，请重试");
						}
						return result;
					}else{
						User addUser = new User();
						addUser.setPhone(phone);
						addUser.setDevicetype(devicetype);
						addUser.setUser_id(GenerateUniqueId.generateUniqueId());
						addUser.setToken(CommonUtils.makeToken(phone));
						int resultcode = userDao.saveUser(addUser);
						if(resultcode>0){
							//初始化我的店铺
							Store store=new Store();
							store.setStore_id(addUser.getUser_id());
							sotreService.createStore(store);
							result.setStatus(1);
							result.setMsg("登录成功");
							result.setData(addUser);
							return result;
						}
					}
				} else if (a < 0) {
					result.setStatus(0);
					result.setMsg("验证码超时,请重新发送!");
					return result;
				} else {
					result.setStatus(0);
					result.setMsg("验证码错误,请重试!");
					return result;
				}
			}
		return result;
	}



	@Override
	public AdResult lockUserPay(String user_id) {
		AdResult adResult=new AdResult();
		//当前时间 
		Date date=new Date();
		User user=new User();
		user.setPay_lock_time(date);
		user.setUser_id(user_id);
		int result_line=userDao.lockUserPay(user);
		if(result_line>0){
			adResult.setMsg("锁定成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("锁定失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult isSettingPayPassword(String user_id,String token) {
		AdResult adResult=new AdResult();
		HashMap<String, String> map=new HashMap<>();
		map.put("user_id",user_id);
		map.put("token",token);
		User user=userDao.getUserInfo(map);
		if(user!=null){
			if(user.getPay_password()==null || user.getPay_password().equals("")){
				adResult.setMsg("未设置");
				adResult.setStatus(1);
			}else{
				adResult.setMsg("已设置");
				adResult.setStatus(2);
			}
		}else{
			adResult.setMsg("获取失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult savePayPassword(String user_id, String paypassword) {
		AdResult adResult=new AdResult();
		User user=new User();
		user.setUser_id(user_id);
		user.setPay_password(EncodeUtil.md5(paypassword));
		int result_lines=userDao.savePayPassword(user);
		if(result_lines>0){
			adResult.setMsg("保存成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("保存失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult checkIsAssociatedAliPay(String user_id, String total_amount,String token) {
		AdResult adResult=new AdResult();
		HashMap<String, String> map=new HashMap<>();
		map.put("user_id",user_id);
		map.put("token",token);
		User user=userDao.getUserInfo(map);
		if(user!=null){
			if(user.getBalance().doubleValue()<Double.parseDouble(total_amount)){
				adResult.setStatus(2);
				adResult.setMsg("余额不足");
			}else if(user.getAlipay()==null || user.getAlipay().isEmpty()){
				adResult.setStatus(3);
				adResult.setMsg("未关联支付宝账号");
			}else{
				adResult.setData(user);
				adResult.setStatus(1);
				adResult.setMsg("可以提现");
			}
		}else{
			adResult.setStatus(0);
			adResult.setMsg("查询用户失败");
		}
		return adResult;
	}
	@Transactional
	@Override
	public AdResult getAllMyPushAds(String user_accept_id,Integer pageIndex,Integer pageSize) {
		AdResult adResult=new AdResult();
		HashMap<String,Object> map=new HashMap<>();
		map.put("user_accept_id", user_accept_id);
		map.put("pageIndex", (pageIndex - 1) * pageSize);
		map.put("pageSize", pageSize);
		List<Push> pushs=userDao.getAllMyPushAds(map);
		System.out.println(user_accept_id);
		User user=userDao.getTotalAward(user_accept_id);
		if(pushs.size()>0){
			adResult.setData(pushs);
			adResult.setMsg("获取成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("没有数据");
			adResult.setStatus(0);
		}
		System.out.println(user);
		if(user!=null){
			adResult.setTotal_award(user.getTotal_award());
		}
		return adResult;
	}

	@Override
	public AdResult getBomb(Double lng, Double lat,Double radius) {
		AdResult adResult=new AdResult();
		List<Ad> bombs=userDao.getBomb();
		Iterator<Ad> iterator = bombs.iterator();
		while (iterator.hasNext()){
			Ad ad = iterator.next();
			Double lng1 = ad.getLon();
			Double lat1 = ad.getLat();
			if(lng1==null || lat1==null){
				iterator.remove();
				continue;
			}
			double getDistance = MapUtils.GetDistance(lng,lat,lng1,lat1);
			if(getDistance>radius){
				iterator.remove();
			}
		}
		if(bombs.size()>0){
			adResult.setMsg("有炸弹");
			adResult.setStatus(1);
			adResult.setData(bombs);
		}else{
			adResult.setMsg("无炸弹");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult getMyConcern(String user_id,Integer pageIndex,Integer pageSize) {
		AdResult adResult=new AdResult();
		HashMap<String, Object> map=new HashMap<>();
		map.put("user_id", user_id);
		map.put("pageIndex", (pageIndex-1)*pageSize);
		map.put("pageSize", pageSize);
		List<Concern> concerns=userDao.getMyConcern(map);
//		if(concerns.size()>0){
//			Ad ad=null;
//			for(int i=0;i<concerns.size();i++){
//				ad=userDao.getFirstAdByUserId(concerns.get(i).getStore_id());
//				if(ad!=null){
//					concerns.get(i).setAd(ad);
//				}
//			}
//			adResult.setData(concerns);
//			adResult.setMsg("获取成功");
//			adResult.setStatus(1);
//		}else{
//			adResult.setMsg("未获取到数据");
//			adResult.setStatus(0);
//		}
		if(concerns.size()>0){
			adResult.setData(concerns);
			adResult.setMsg("获取成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("未获取到数据");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult getMyCollection(String user_id, Integer pageIndex, Integer pageSize) {
		AdResult adResult=new AdResult();
		HashMap<String, Object> map=new HashMap<>();
		map.put("user_id", user_id);
		map.put("pageIndex", (pageIndex-1)*pageSize);
		map.put("pageSize", pageSize);
		ArrayList<CollectionAd> collections=userDao.getMyCollection(map);
		List<Ad> ads=new ArrayList<>();
		if(collections.size()>0){
			Ad ad=null;
			for(int i=0;i<collections.size();i++){
				ad=addao.getAdById(collections.get(i).getAd_id());
				if(ad!=null){
					ads.add(ad);
				}
			}
			adResult.setData(ads);
			adResult.setMsg("获取成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("未获取到数据");
			adResult.setStatus(0);
		}
		return adResult;
	}
	
	public AdResult feedBack(Feed feed,HttpServletRequest request,CommonsMultipartFile file){
		AdResult adResult=new AdResult();
		//图片路径
		String imagePath="";
		//相对路径
		String relativePath="";
		//根路径
		String rootPath=request.getSession().getServletContext().getRealPath(File.separator);
		if(file!=null && !file.isEmpty()){
			relativePath="upload"+File.separator+"feed"+File.separator+new Date().getTime()+file.getOriginalFilename();
			imagePath=rootPath+relativePath;
			File feedImage=new File(imagePath);
			try {
				InputStream in=file.getInputStream();
				FileOutputStream fos=new FileOutputStream(feedImage);
				int len=-1;
				byte[] bytes=new byte[1024];
				while((len=in.read(bytes))!=-1){
					fos.write(bytes, 0, len);
				}
				in.close();
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		feed.setPhoto(relativePath);
		int resultCode=userDao.feedBack(feed);
		if(resultCode>0){
			adResult.setMsg("提交成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("提交失败");
			adResult.setStatus(0);
		}
		return adResult;
	}
	
	

}
